<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/9/6
 * Time: 9:06
 */
class ASSUserController extends BaseController
{
    /**
     * @var array 返回数据模板
     */
    protected $response = ['code' => 0, 'msg' => 'ok'];
    /**
     * @var object 用户信息
     */
    protected $user;

    /**
     * @Description  pms平台创建用户
     * @return string
     * @author yyc
     * @date 2018/9/6 11:54
     */
    public function create()
    {
        $validator = Validator::make(Input::all(), [
            'token' => 'required|string',
            'userName' => 'required',
            'password' => 'required',
            'id' => 'required|integer|',
            'assId' => 'integer',
        ]);
        do {
            //验证参数信息
            if($validator->fails()) {
                $this->response = Lang::get('ass_error.args_error_100000');
                $this->response['result'] = $validator->messages();
                break;
            }

            //验证pms用户状态
            $this->user = $this->verificationPMSUserToken(Input::get('token'), $this->response);

            if ($this->user['status'] == 0) {
                $this->response = $this->user['response'];
                break;
            }

            $userName = trim(Input::get('userName'));       //登录账号
            $assId = trim(Input::get('assId', ''));        //ass 平台ID
            $password = trim(Input::get('password'));       //密码

            //验证pms供应商是否存在
            $supplier = MaintenanceSupplier::find(Input::get('id'));
            if (is_null($supplier)) {
                $this->response = Lang::get('ass_error.create_user_error_100004');
                break;
            }

            //验证pms供应商合作状态是否正常  (1:合作正常;2:暂停合作;3:终止合作;)
            if ($supplier->work_together_type != 1) {
                $this->response = Lang::get('ass_error.create_user_error_100005');
                break;
            }

            //判断ASS系统登录名是否已经存在
            $existUser = ASSUser::where('user_name', $userName);
            if ($assId != '') {             //修改
                $existUser->where('id', $assId);
            }
            $existUser = $existUser->first();

            //验证用户是否已经存在   添加的时候
            if($existUser && $assId == ''){
                $this->response = Lang::get('ass_error.create_user_error_100008');
                break;
            }

            //验证是否已经创建用户
            if ($assId == '') {
                if (!is_null(ASSUser::where('pms_supplier_id', $supplier->id)->first())) {
                    $this->response = Lang::get('ass_error.create_user_error_100007');
                    break;
                }
            }

            //组织新增供应商到ASS
            if ($assId == '') {
                $supplierNew = new ASSUser();
                $supplierNew->work_together_type_ass = $supplier->work_together_type;
                $supplierNew->pms_supplier_id = $supplier->id;
                $supplierNew->updated_at = Common::num2DateTime(time());
                $supplierNew->updated_type = 1;             //ass平台用户
                $supplierNew->created_by = $this->user['user']['id'];
            } else {    //修改用户信息
                $supplierNew = ASSUser::find($assId);
                $supplierNew->created_at = Common::num2DateTime(time());
                $supplierNew->updated_type = 1;         //pms 平台修改人
                $supplierNew->updated_by = $this->user['user']['id'];
            }

            $supplierNew->user_name = $userName;
            $supplierNew->password = Common::make(strtoupper($password));

            //添加处理
            try {
                $supplierNew->save();
            } catch (Exception $e) {
                Log::info('info', ['system' => 'ass', 'event' => 'user/create', 'input' => Input::all(), 'output' => $this->response]);
                $this->response = Lang::get('ass_error.create_user_error_100006');
                break;
            }

        } while (false);
        Log::info('info', ['system' => 'ass', 'event' => 'user/create', 'input' => Input::all(), 'output' => $this->response]);
        return json_encode($this->response);
    }

    /**
     * @Description ass平台修改用户信息
     * @return string
     * @author yyc
     * @date 2018/9/6 17:20
     */
    public function store()
    {
        $validator = Validator::make(Input::all(), [
            'token' => 'required|string',
            'password' => 'required',
            'oldPassword' => 'required',
            'id' => 'required|integer',
        ]);
        do {
            //验证参数信息
            if($validator->fails()) {
                $this->response = Lang::get('ass_error.args_error_100000');
                $this->response['result'] = $validator->messages();
                break;
            }

            $this->user = $this->verificationASSUserToken(Input::get('token'), $this->response);

            $oldPassword = Input::get('oldPassword', '');
            $password = Input::get('password', '');
            //验证用户
            if (!is_null($this->user)) {
                if($this->user->password != Common::make(strtoupper($oldPassword))){
                    $this->response = Lang::get('ass_error.store_user_error_100001');
                    break;
                }
            } else {
                $this->response = Lang::get('ass_error.args_error_100003');
                break;
            }

            //获取要修改的人员信息
            $supplier = ASSUser::find($this->user->ass_user_id);
            $supplier->password = Common::make($password);
            $supplier->updated_by = $this->user->ass_user_id;
            $supplier->updated_at = Common::num2DateTime(time());
            $supplier->updated_type = 2;

            try {
                $supplier->save();
            } catch (Exception $e) {
                Log::info('info', ['system' => 'ass', 'event' => 'user/store', 'input' => Input::all(), 'output' => $this->response]);
                $this->response = Lang::get('ass_error.store_user_error_100001');
                break;
            }
        } while (false);

        Log::info('info', ['system' => 'ass', 'event' => 'user/store', 'input' => Input::all(), 'output' => $this->response]);
        return json_encode($this->response);
    }

    /**
     * @Description  登出
     * @return string
     * @author yyc
     * @date 2018/9/6 17:21
     */
    public function logout()
    {
        $validator = Validator::make(Input::all(), [
            'token' => 'required|string',
        ]);
        do {
            //验证参数信息
            if($validator->fails()) {
                $this->response = Lang::get('ass_error.args_error_100000');
                $this->response['result'] = $validator->messages();
                break;
            }
            //验证用户
            $this->user = $this->verificationASSUserToken(Input::get('token'), $this->response);
            if(is_null($this->user)){
                break;
            }

            //删除token
            try{
                ASSUserToken::where('ass_user_id', $this->user->ass_user_id)->delete();

            } catch (Exception $e) {
                Log::info('info', ['system' => 'oa', 'event' => 'user/logout', 'input' => Input::all(), 'exception' => $e]);
                $this->response = Lang::get('ass_error.args_error_100004');
                break;
            }

        } while (false);
        Log::info('info', ['system' => 'ass', 'event' => 'user/logout', 'input' => Input::all(), 'output' => $this->response]);
        return json_encode($this->response);
    }

    /**
     * @Description 登录
     * @return string
     * @author yyc
     * @date date
     */
    public function login()
    {
        $validator = Validator::make(Input::all(), [
            'userName' => 'required',
            'password' => 'required',
        ]);
        do {
            //验证参数信息
            if($validator->fails()) {
                $this->response = Lang::get('ass_error.args_error_100000');
                $this->response['result'] = $validator->messages();
                break;
            }

            //获取用户信息并处理
            $userName   = Input::get('userName');                           //用户名
            $password   = Common::make(Input::get('password'));             //密码
            $this->user = ASSUser::findUserByUP($userName, $password);      //验证密码
            $token = md5($userName. time(). rand(0, 100));

            //验证用户信息书否正确
            if (is_null($this->user)) {                                     //用户名密码
                $this->response = Lang::get('ass_error.login_user_status_error_210005');
                break;

            } else {                                                        //供应商状态
                if ($this->user->work_together_type_ass != 1) {
                    $this->response = Lang::get('ass_error.create_user_error_100005');
                    break;
                }
            }

            DB::beginTransaction();
            try {
                //删除token并重新创建
                ASSUserToken::where('ass_user_id', $this->user->id)->delete();
                $AssToken = new ASSUserToken();
                $AssToken->ass_user_id = $this->user->id;
                $AssToken->token = $token;
                $AssToken->created_at = Common::num2DateTime(time());
                $AssToken->updated_at = Common::num2DateTime(time());
                $AssToken->out_time_at = Common::num2DateTime(time() + 60*60*24);
                $AssToken->save();

                //处理返回数据
                $this->user = $this->verificationASSUserToken($token, $this->response);
                if(is_null($this->user)){
                    break;
                }

                //处理登录次数
                $dateTime = Common::datetime2Num(date('Y-m', time()));

                $dataNum = ASSLoginData::where('pms_supplier_id', $this->user->id)->where('login_date', $dateTime)->first();
                if (is_null($dataNum)) {
                    //当天没有登录过
                    $dataNum = new ASSLoginData();
                    $dataNum->pms_supplier_id = $this->user->id;
                    $dataNum->ass_supplier_id = $this->user->ass_user_id;
                    $dataNum->login_num_day = 1;
                    $dataNum->login_date = $dateTime;
                    $dataNum->created_at = Common::num2DateTime(time());
                    $dataNum->created_by = $this->user->ass_user_id;
                } else {
                    //当天登录过,则增加一次
                    $dataNum->login_num_day += 1;
                    $dataNum->updated_at = Common::num2DateTime(time());
                    $dataNum->updated_by = $this->user->ass_user_id;;
                }
                //登录流水表
                $dataNum->save();
                $flow = new ASSLoginFlow();
                $flow->created_at = Common::num2DateTime(time());
                $flow->created_by = $this->user->ass_user_id;
                $flow->pms_supplier_id = $this->user->id;
                $flow->ass_supplier_id = $this->user->ass_user_id;
                $flow->login_date = $dateTime;
                $flow->save();
                $this->response['result'] = $this->user;
                DB::commit();
            } catch (Exception $e) {
                DB::rollBack();
                Log::info('info', ['system' => 'oa', 'event' => 'user/login', 'input' => Input::all(), 'exception' => $e]);
                $this->response = Lang::get('ass_error.login_user_status_error_210005');
                break;
            }

        } while (false);

        Log::info('info', ['system' => 'ass', 'event' => 'user/login', 'input' => Input::all(), 'output' => $this->response]);
        return json_encode($this->response);

    }

    /**
     * @Description 登录次数列表
     * @author yyc
     * @date 2018/9/7 9:10
     */
    public function supplierLoginInfo()
    {
        $validator = Validator::make(Input::all(), [
            'token' => 'required|string',
        ]);
        do {
            //验证参数信息
            if($validator->fails()) {
                $this->response = Lang::get('ass_error.args_error_100000');
                $this->response['result'] = $validator->messages();
                break;
            }

            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $this->response = $res['response'];
                break;
            }

            $id = Input::get('id', '');
            $page = Input::get('page', 1);
            $pageSize = Input::get('pageSize', 20);
            $date = Input::get('date', '');

            $dateAll = ASSLoginData::supplierLoginData($page, $pageSize, $date, $id);

            $this->response = [
                'code' => 0,
                'msg' => 'ok',
                'result' => [
                    'count' => $dateAll['count'],
                    'loginData' => $dateAll['result'],
                    'supplier'  => ASSLoginData::supplierListPms(),
                ],
            ];

        } while (false);
        return json_encode($this->response);
    }

}